(function($){
    var userName=localStorage.chat_name;
    if(userName){

        var socket;
        var firstconnect = true;
        var sid;
        var $txtContent=$('#txtContent');
        var $msgList=$('#msgList');
        var isActiveWindow=true;
        var msgCount=0;

        //添加鼠标焦点移入浏览器窗口事件
        window.addEventListener('focus', function() {
            isActiveWindow=true;
            msgCount=0;
            document.title="Let's Chat";
        },false);

        //添加鼠标焦点移开浏览器窗口事件
        window.addEventListener('blur', function() {
            isActiveWindow=false;
        },false);

        function connect() {
            if(firstconnect) {
                socket = io.connect('localhost:3003');
                socket.on('message', function(data){
                    var sb='<li class="am-text-center"><small>'+new Date().toLocaleString()+'</small></li>';
                    sb+='<li class="chat-item '+(data.sender==userName?'right':'left')+'">';
                    sb+='<span>'+data.sender+'</span>';
                    sb+='<div>'+data.msg+'</div>';
                    sb+='</li>';
                    $msgList.append(sb);
                    $msgList.parent().smoothScroll({position: $msgList.height() - $msgList.parent().height()});

                    if(!isActiveWindow){
                        msgCount++;
                        document.title='（你有'+msgCount+'条未渎消息！）';
                    }
                });
                socket.on('connect', function(){
                    status_update('连接成功');
                    sid=socket.io.engine.id;
                    socket.emit('newUser', {userName:userName});
                });
                socket.on('disconnect', function(){ status_update("已断开连接"); });
                socket.on('reconnect', function(){ status_update("重新连接成功"); });
                socket.on('reconnecting', function( nextRetry ){ status_update("重新连接中 "
                    + nextRetry + " s"); });
                socket.on('reconnect_failed', function(){ message("连接失败"); });

                socket.on('userList', function(data){
                    var sb='';
                    data.userList.forEach(function(name){
                        sb+='<li><i class="am-icon-user"></i> '+name+'</li>';
                    });
                    $('#userList').html(sb);
                });

                firstconnect = false;
            } else {
                socket.io.reconnect();
            }
        }

        function disconnect() {
            socket.disconnect();
        }

        function status_update(txt){
            $('#status').html(txt);
        }

        function send(msg) {
            var content=msg||$txtContent.html();
            if(content) {
                socket.send(content);
            }else{
                alert('内容不能为空！');
            }
            $txtContent.html('');
        }

        //加载QQ表情
        function loadQqFace(){
            var sb='';
            for(var i=1;i<=75;i++){
                sb+='<a href="javascript:;" title=""><img src="images/qq_face/'+i+'.gif"/></a>';
            }
            $('#qqFace').html(sb);
        }

        //加载emoji表情
        function loadEmojiFace(){
            var sb='';
            for(var i=0;i<168;i++){
                sb+='<a href="javascript:;" class="icon-emoji'+i+'" title=""></a>';
            }
            $('#emoji').html(sb);
        }

        function previewImage(file) {
            var MAXWIDTH  = $(window).width();
            var MAXHEIGHT = $(window).height()-50;
            if (file.files && file.files[0]){
                if(file.files[0].type.indexOf('image/')<0){
                    alert('请选择合适的图片格式文件');
                    return;
                }
                var img = document.getElementById('imghead');
                img.onload = function(){
                    //按最大高宽缩放图片
                    var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
                    img.width = rect.width;
                    img.height = rect.height;
                    //img.style.marginLeft = rect.left+'px';
                    //img.style.marginTop = rect.top+'px';
                };
                var reader = new FileReader();
                //获取数据源后触发此事件
                reader.onload = function(evt){
                    //移除之前图片的高宽，防止沿用
                    img.removeAttribute('width');
                    img.removeAttribute('height');
                    //把数据源的base64编码赋给图片链接
                    img.src = evt.target.result;
                };
                //从file input获取数据源
                reader.readAsDataURL(file.files[0]);
            }
        }
        function clacImgZoomParam( maxWidth, maxHeight, width, height ){
            var param = {top:0, left:0, width:width, height:height};
            if( width>maxWidth || height>maxHeight ){
                var rateWidth = width / maxWidth;
                var rateHeight = height / maxHeight;
                if( rateWidth > rateHeight ){
                    param.width =  maxWidth;
                    param.height = Math.round(height / rateWidth);
                }else{
                    param.width = Math.round(width / rateHeight);
                    param.height = maxHeight;
                }
            }
            param.left = Math.round((maxWidth - param.width) / 2);
            param.top = Math.round((maxHeight - param.height) / 2);
            return param;
        }

        function clearFileInput(file){
            if(file.value){
                var form=document.createElement('form');
                var ref=file.nextSibling;   //如果有下个兄弟节点
                var parent=file.parentNode;
                form.appendChild(file);
                form.reset();
                parent.insertBefore(file,ref);
            }
        }

        //在光标处插入内容，可指定容器
        function insertAtCursor(content, container){
            var selection=window.getSelection();
            var range;
            //判断全局的选择是否指定区域内
            if(container&&!$(selection.anchorNode).closest(container).length){
                container.focus();
                range=document.createRange();
                range.selectNodeContents(container);
                range.setStart(container, container.childNodes.length);
            }else{
                range=selection.getRangeAt(0);
            }
            //备份要插入的内容（图片）
            var img=$(content)[0];
            //插入到范围的开始点
            range.insertNode(img);
            //设置范围的开始点到插入的内容之后（即把光标显示在插入内容之后，否则是在之前的）
            range.setStartAfter(img);
            //刷新选择的内容（一个Selection只允许有一个Range，因这里的Range有改变过，故需在add前清除掉）
            selection.removeAllRanges();
            selection.addRange(range);
        }

        connect();
        loadQqFace();
        loadEmojiFace();

        $('.emotion-tabs').slimscroll({
            height:180,
            width:435
        });

        $(document)
            //发送
            .on('click', '#btnSend', function(){
                send();
            })
            .on('keydown', '#txtContent', function(e){
                if(e.keyCode==13){
                    if(!e.shiftKey){
                        //Enter发送，Shift+Enter发送
                        send();
                        return false;
                    }
                }
            })
            //选择QQ表情
            .on('click', '#qqFace a', function(){
                insertAtCursor($(this).html(), $txtContent[0]);
                $('#ddFace').dropdown('close');
            })
            //选择emoji表情
            .on('click', '#emoji a', function(){
                insertAtCursor('<img class="'+this.className+'" src="./images/1.gif"/>', $txtContent[0]);
                $('#ddFace').dropdown('close');
            })
            //选择图片
            .on('click', '#btnPicture', function(){
                $('#filePicture').trigger('click');
            })
            .on('change', '#filePicture', function(){
                previewImage(this);
                $('#modalPicture').modal('open');
                clearFileInput(this);
            })
            //发送图片
            .on('click', '#btnSendPicture', function(){
                send('<img class="msg-picture" title="点击查看原图" style="max-width:300px;" src="'+$('#imghead').attr('src')+'"/>');
                $('#modalPicture').modal('close');
            })
            .on('click', 'img.msg-picture', function(){
                var $img=$('<img>').attr({
                    src:this.src,
                    style:'max-width:100%;max-height:100%;-webkit-user-select:none'
                });
                    $('<div title="双击关闭">').css({
                        position:'fixed',
                        left:0,
                        top:0,
                        width:'100%',
                        height:'100%',
                        textAlign:'center',
                        background:'rgba(0,0,0,.8)'
                    })
                        .append($img).appendTo($('body'))
                .on('dblclick', function(){
                    $(this).remove();
                });
            })
            //选择文件
            .on('click', '#btnFile', function(){
                $('#fileUpload').trigger('click');
            })
            .on('change', '#fileUpload', function(){
                var file=this;
                $('#modalFile').find('strong').html(file.files[0].name).end()
                    .modal({
                        onConfirm:function(){
                            var $btn=$('#btnFile').hide();
                            var $progress=$('#progress').removeClass('am-hide');
                            var $progressBar=$progress.find('.am-progress-bar:first');
                            var fileObj = file.files[0]; // 获取文件对象
                            // FormData 对象
                            var form = new FormData();
                            form.append("file", fileObj);                           // 文件对象
                            // XMLHttpRequest 对象
                            var xhr = new XMLHttpRequest();
                            xhr.open("post", "/chatsapi/upload", true);
                            xhr.onload = function () {//console.log(JSON.parse(this.response));
                                alert("上传完成!");
                                $btn.show();
                                $progress.addClass('am-hide');
                                clearFileInput(file);
                            };
                            xhr.upload.addEventListener('progress', function(e){
                                if (e.lengthComputable) {
                                    var percentComplete = Math.round(e.loaded * 100 / e.total);
                                    $progressBar.css('width', percentComplete+'%');
                                }else {
                                    alert('解析文件失败！');
                                    $btn.show();
                                    $progress.addClass('am-hide');
                                    clearFileInput(file);
                                }
                            }, false);
                            xhr.send(form);
                        },
                        onCancel:function(){
                            clearFileInput(file);
                        }
                    });
            })
            //打开文件库
            .on('open.dropdown.amui', '#ddFileLib', function(){
                $.ajax({
                    url:'/chatsapi/file',
                    dataType:'json',
                    success:function(data){
                        var list=data.data;
                        var sb='';
                        list.forEach(function(f){
                            var ext=f.name.substr(f.name.lastIndexOf('.'));
                            var icon='text-o';
                            switch (ext){
                                case '.xls':
                                case '.xlsx':
                                    icon='excel-o';
                                    break;
                                case '.ppt':
                                case '.pptx':
                                    icon='powerpoint-o';
                                    break;
                                case '.doc':
                                case '.docx':
                                    icon='word-o';
                                    break;
                                case '.zip':
                                case '.rar':
                                case '.tar':
                                case '.gz':
                                case '.jar':
                                    icon='archive-o';
                                    break;
                                case '.mp3':
                                case '.ogg':
                                case '.wmv':
                                    icon='audio-o';
                                    break;
                                case '.jpg':
                                case '.jpeg':
                                case '.gif':
                                case '.png':
                                case '.bmp':
                                    icon='image-o';
                                    break;
                                case '.pdf':
                                    icon='pdf-o';
                                    break;
                            }
                            sb+='<tr><td><i class="am-icon-file-'+icon+'"></i> '+f.name+'</td><td class="am-text-right">'+f.size+'</td><td class="am-text-nowrap">'+f.date+'</td><td><a href="./upload/'+f.name+'" download title="下载"><i class="am-icon-download"></i> </a></td></tr>';
                        });
                        $('#fileList').html(sb);
                    }
                });
            })
            //退出
            .on('click', '#btnExit', function(){
                delete localStorage.chat_name;
                location.href='login.html';
            })
        ;
    }else{
        location.href='login.html';
    }
})(jQuery);